package com.aptemo.webetek.client;

import com.aptemo.webetek.client.properties.WebetekConstants;
import com.aptemo.webetek.client.properties.WebetekMessages;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Webetek implements EntryPoint
{

	/**
	 * An aggregate image bundle that pulls together all the images for this
	 * application into a single bundle.
	 */
	// public interface Images extends Shortcuts.Images, TopPanel.Images {
	// }

	private static WebetekConstants	constants	= GWT.create(WebetekConstants.class);
	private static WebetekMessages	messages	= GWT.create(WebetekMessages.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad()
	{
		HandlerManager eventBus = new HandlerManager(null);
		WebetekUserServiceAsync rpcService = GWT.create(WebetekUserService.class);

		String curLoc = LocaleInfo.getCurrentLocale().getLocaleName();
		String language = Cookies.getCookie("language");
		if (language == null && curLoc.equals("default"))
		{
			// save default locale...
			Cookies.setCookie("language", curLoc);
		}

		if ((language != null && !curLoc.equals(language)))
		{
			setSelectedLanguage(language);
		}

		// WebetekResources.INSTANCE.css().ensureInjected();
		// init layout widget...
		WebetekLayout layout = new WebetekLayout();
		// layout.getTopPanel().add(new Label(constants.loading()));
		WebetekLayoutPresenter app = new WebetekLayoutPresenter(layout, rpcService, eventBus);
		app.go(null);
	}

	public static WebetekConstants getConstants()
	{
		return constants;
	}

	public static WebetekMessages getMessages()
	{
		return messages;
	}

	private boolean setSelectedLanguage(String locale)
	{
		if ((locale != null) && (!locale.isEmpty()))
		{

			String path = Window.Location.getPath();
			String query = Window.Location.getQueryString();
			if (!query.isEmpty())
			{
				// check for locale
				if (query.contains("locale="))
				{
					int i1 = query.indexOf("locale=");
					int i2 = query.indexOf("&", i1 + 1);
					if (i2 == -1)
					{
						i2 = query.length();
					}
					String tmp = query.substring(i1, i2);
					query = query.replaceAll(tmp, "");

				}
				else
				{
					query += "&";
				}
			}
			else
			{
				query += "?";
			}
			query += "locale=" + locale;

			// if english - don't touch...
			// if (locale.equals("en"))
			// {
			//
			// }
			// else
			// {
			Window.Location.replace(path + query + Window.Location.getHash());
			// }

			// save cookie
			Cookies.setCookie("language", locale);

			return true;
		}

		return false;
	}

}
